<template>
  <div class="bgy-account-index fiexBox">
    <section class="tavle-content">
      <!-- 头部 -->
      <el-header height="auto">
        <!-- 搜索 -->
        <el-form :inline="true" :model="formData" class="demo-form-inline heard-search" @submit.native.prevent>
          <el-form-item label="所属主体:">
            <el-select v-model="formData.mainbodyId" clearable filterable :default-first-option="true" placeholder="请选择">
              <el-option v-for="(item, index) in selectOptions.mainbody" :key="index" :label="`${item.id} - ${item.name}`" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户账号:">
            <el-input v-model="formData.account" placeholder="按用户账号搜索"></el-input>
          </el-form-item>
          <el-form-item label="手机号:">
            <el-input v-model="formData.mobile" placeholder="按用手机号搜索"></el-input>
          </el-form-item>
          <el-form-item label="在线状态:">
            <el-select v-model="formData.isOnline" clearable filterable :default-first-option="true"  placeholder="请选择">
              <el-option label="请选择" value=""></el-option>
              <el-option label="在线" value="true"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态:">
            <el-select v-model="formData.status" clearable filterable :default-first-option="true"  placeholder="请选择">
              <el-option label="请选择" value=""></el-option>
              <el-option label="正常" value="2"></el-option>
              <el-option label="已禁用" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" icon="el-icon-zoom-out" type="primary" @click="search">搜索</el-button>
            <el-button size="small" icon="el-icon-plus" type="primary" @click="addEdit('add')">添加账号</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <!-- 表格 -->
      <el-main>
        <section ref="account_main_table" class="row-table">
          <el-table
            class="rowtable"
            :data="tableData"
            highlight-current-row
            @row-dblclick="tableClick"
            v-loading="isShowLoading"
            stripe
            :max-height="tableHeight"
            style="width: 100%">
            <el-table-column
              v-if="item.isShow"
              v-for="(item, index) in tableHeaderData"
              :key="index"
              :prop="item.prop"
              :width="item.width"
              align="left"
              :show-overflow-tooltip="true"
              :label="item.label">
              <template slot-scope="scope">
                <span v-if="item.prop === 'type' ">{{scope.row[item.prop] == 1? '平台': '普通'}}</span>
                <span v-else-if="item.type === 'time'">{{ dateToString(scope.row[item.prop]) }}</span>
                <span v-else-if="item.prop === 'online'">{{ scope.row[item.prop]? '在线': '-' }}</span>
                <span v-else-if="item.prop === 'status'">
                  <template v-if="scope.row[item.prop] == 1">待审核</template>
                  <template v-if="scope.row[item.prop] == 2">正常</template>
                  <template v-if="scope.row[item.prop] == 3">禁用</template>
                </span>
                <span v-else-if="scope.row[item.prop]">{{scope.row[item.prop]}}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              align="left"
              width="150">
              <template slot="header" slot-scope="scope">
                <div>操作<table-heard-option :tableHeaderData="tableHeaderData"></table-heard-option></div>
              </template>
              <template slot-scope="scope">
                <el-button type="text" size="medium" class="p3" @click="addEdit('edit', scope.row)">编辑</el-button>
                <el-popconfirm
                  v-is-iac="'customer-del'"
                  confirm-button-text='好的'
                  cancel-button-text='不用了'
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定要删除该当前申请吗？">
                  <el-button slot="reference" type="text" size="medium" class="p3" @click="addEdit('delet', scope.row)">删除</el-button>
                </el-popconfirm>
                <!-- <el-button type="text" size="medium" class="p3" @click="addEdit('delet', scope.row)">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </section>
      </el-main>

      <!-- 分页 -->
      <el-footer height="auto">
        <div class="block-pagination r clearfix">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="formData.page"
            :page-sizes="[20, 50, 100, 200]"
            :page-size="formData.limit"
            layout="total, prev, pager, next, sizes, jumper"
            :total="totalCont">
          </el-pagination>
        </div>
      </el-footer>
    </section>
    <!-- 弹窗表单 -->
    <prop-form :propOptions="propOptions" :propformHeard="propformHeard" :propSubmit="propSubmit" :propSelect="propSelect"></prop-form>
  </div>
</template>

<script>
import { mapState,mapMutations } from 'vuex';
import { accountList, createAccount, getAccount, editAccount, delAccount } from '@/axios/system/account';
import { dateToString } from '@/utils/util';
import { mainbodyAll, departmentAll, roleAll } from '@/axios/api';
import elementResizeDetectorMaker from "element-resize-detector";
import Sortable from 'sortablejs';

var viewer = null;
export default {
  name: 'account',
  data () {
    return {
      formData: {
        page: 1,
        limit: 20
      },
      selectOptions: {
        role: [], // 角色
        mainbody: [], // 所属主体
        department: [], // 所属部门
      },
      totalCont: 0,
      isShowLoading: false,
      tableHeight: 0,
      tableHeaderData: [
        { label: '客户名称', prop: 'type', width: '100', isShow: true },
        { label: '客户全称', prop: 'mainbodyName', width: '300', isShow: true },
        { label: '客户联系人', prop: 'account', width: '200', isShow: true },
        { label: '客户联系电话', prop: 'name', width: '', isShow: true },
        { label: '账期', prop: 'departmentName', width: '190', isShow: true },
        { label: '在线状态', prop: 'online', width: '100', isShow: true },
        { label: '最后访问', prop: 'lastReqUri', isShow: true },
        { label: '状态', prop: 'status', width: '100', isShow: true }
      ],
      tableData: [],
      // 弹窗表单
      propOptions: {
        title: '客户信息',
        isShow: false,
        submitType: '',
        buttons: [
          { type: 'save', name: '保存' }
        ]
      },
      propformHeard: [],

    }
  },
  computed:{
    ...mapState([])
  },
  watch: {
  },
  components: {
    tableHeardOption: resolve => {require(['@/components/tools/tableHeardOption/index'], resolve)}, // 表头选择器
    propForm: resolve => {require(['@/components/tools/propForm/index'], resolve)}, // 弹出表单
  },
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
     };
    this.rowDrop()
    this.columnDrop()
    this.watchSize();
    this.init()
  },
  created(){
    localStorage.setItem('authOptions' , JSON.stringify(['customer-del1']))
    this.getTableList();
  },
  methods: {
    ...mapMutations([
      'SAVE_TOKEN',
      'SAVE_EDITABLETABS'
    ]),
    // 初始化
    init() {
      mainbodyAll({
          limit: 10000
      }).then(res => {
          if (res.code === 0) {
              res.data.forEach(item => {
                item.name = item.shortName
                item.code = item.id
              })
              this.selectOptions.mainbody = res.data
          }
      })
    },
    /**
     * @method 监听表格流体高度
     */
    watchSize() {
      const _this = this;
      var erd = elementResizeDetectorMaker();
      erd.listenTo(this.$refs.account_main_table, (element) => {
        var width = element.offsetWidth;
        var height = element.offsetHeight;
        _this.$nextTick(() => { // 这里填写监听改变后的操作
          _this.tableHeight = height
        });
      });
    },
    async getTableList() {
      this.isShowLoading = true
      // let data = await accountList(this.formData)
      // if (data.code === 0) {
      //   this.tableData = data.data
      //   this.totalCont = data.count
      // }
      this.tableData = [{account: 'admin', id: 1}]
      this.isShowLoading = false
    },
    search(param) {
      if (param === 'reset') {
        this.formData.searchValue = ''
        this.formData.mainbodyId = ''
        this.formData.status = ''
      }
      this.getTableList()
    },
    // 每页数量变更
    handleSizeChange(val) {
      this.formData.page = 1
      this.formData.limit = val
      this.getTableList()
    },
    // 翻页切换变更
    handleCurrentChange(val) {
      this.formData.page = val
      this.getTableList()
    },
    /**
     * @method 表格点击
     */
    tableClick(row, column) {
      this.addEdit('edit', row)
    },
    // 时间格式
    dateToString(time) {
      return dateToString(time, 'yyyy-mm-dd')
    },
     //行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
          _this.tableData.splice(newIndex, 0, currRow)
        }
      })
    },
    //列拖拽
    columnDrop() {
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr')
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: evt => {
          this.isShowLoading = true
          let data = JSON.parse(JSON.stringify(this.tableHeaderData))
          swapArr(data, evt.oldIndex, evt.newIndex)
          this.tableHeaderData = []
          this.$nextTick(() => {
            this.tableHeaderData = data
            this.isShowLoading = false
          })
        }
      })
      function swapArr(arr, index1, index2) {
          arr[index1] = arr.splice(index2, 1, arr[index1])[0];
          return arr;
      }
    },
    // 弹窗表单按钮点击
    propSubmit(option) {
      if (this.propOptions.submitType === 'add') {
        // 添加
        createAccount(option.data).then(res => {
          if (res.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.propOptions.isShow = false
            this.getTableList()
          }
        })
      } else if (this.propOptions.submitType === 'edit') {
        option.data.isSale = 0
        editAccount(option.data, this.propOptions.id).then(res => {
          if (res.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.propOptions.isShow = false
            this.getTableList()
          }
        })
      }
    },
    // 弹窗下拉选择
    propSelect(option) {
      if (option.key === 'type') {
        if (option.value === 1) {
          // 平台
          roleAll({
              limit: 10000,
              owner: 0
          }).then(res => {
              if (res.code === 0) {
                res.data.forEach(item => {
                  item.code = item.id
                })
                this.propformHeard.forEach(prop => {
                  if (prop.key === 'roleIds') {
                    prop.option = res.data
                  }
                })
              }
          })
          this.propformHeard.forEach(item => {
            if (item.key === 'platformMainbodyId' || item.key === 'departmentId') {
              item.isHide = true
              item.disabled = true
            }
          })
        } else {
          this.propformHeard.forEach(item => { item.isHide = false; item.disabled = false })
        }
      } else if (option.key === 'platformMainbodyId') {
        // 角色
        roleAll({
            limit: 10000,
            owner: option.value
        }).then(res => {
            if (res.code === 0) {
              res.data.forEach(item => {
                item.code = item.id
              })
              this.propformHeard.forEach(prop => {
                if (prop.key === 'roleIds') {
                  prop.option = res.data
                }
              })
            }
        })
        // 部门
        departmentAll({
            limit: 10000,
            mainbody: option.value
        }).then(res => {
            if (res.code === 0) {
              res.data.forEach(item => {
                item.code = item.id
              })
              this.propformHeard.forEach(prop => {
                if (prop.key === 'departmentId') {
                  prop.option = res.data
                }
              })
            }
        })
      }
    },
    // 表格操作
    addEdit(type, obj) {
      this.propOptions.submitType = type
      this.propOptions.id = obj ? obj.id : ''
      if (type === 'add') {
        this.initPropForm(type)
        this.propformHeard = [
          { colSpan: 24, type: 'select', key: 'type', value: '', isRequired: true, disabled: false, label: '用户类型：', labelWidth: '90px', option: [{ name: '平台用户', id: 1}, { name: '普通用户', id: 2}]},
          { colSpan: 24, type: 'select', key: 'platformMainbodyId', value: '', isRequired: true, disabled: false, label: '所属主体：', labelWidth: '90px', option: this.selectOptions.mainbody},
          { colSpan: 24, type: 'input', key: 'accountName', value: '',placeholder: '用于登录系统的账号', isRequired: true, disabled: false, label: '账号：', labelWidth: '90px' },
          { colSpan: 24, type: 'input', inputType: 'password', key: 'password', value: '',placeholder: '登录系统时的密码', isRequired: true, disabled: false, label: '密码：', labelWidth: '90px' },
          { colSpan: 24, type: 'input', key: 'name', value: '', isRequired: true, disabled: false, label: '姓名：', labelWidth: '90px' },
          { colSpan: 24, type: 'input', key: 'mobile', value: '', isRequired: false, disabled: false, label: '手机号：', labelWidth: '90px' },
          { colSpan: 24, type: 'select', key: 'departmentId', value: '', isRequired: true, disabled: false, label: '所属部门：', labelWidth: '90px', option: []},
          { colSpan: 24, type: 'select', key: 'roleIds', value: '', isRequired: true, disabled: false, label: '用户角色：', labelWidth: '90px', option: []},
          { colSpan: 24, type: 'select', key: 'status', value: '', isRequired: true, disabled: false, label: '账号状态：', labelWidth: '90px', option: [{ name: '正常', id: 2}, { name: '禁用(无法登录)', id: 3}]}
        ]
        this.propOptions.isShow = true
      } else if (type === 'edit') {
        this.propformHeard = [
          { colSpan: 24, type: 'text', key: 'mainbodyName', value: '', label: '所属主体：', labelWidth: '90px'},
          { colSpan: 24, type: 'text', key: 'account', value: '', label: '账号：', labelWidth: '90px' },
          { colSpan: 24, type: 'input', inputType: 'password', key: 'password', value: '',placeholder: '登录系统时的密码', isRequired: true, disabled: false, label: '密码：', labelWidth: '90px' },
          { colSpan: 24, type: 'input', key: 'name', value: '', isRequired: true, disabled: false, label: '姓名：', labelWidth: '90px' },
          { colSpan: 24, type: 'input', key: 'mobile', value: '', isRequired: false, disabled: false, label: '手机号：', labelWidth: '90px' },
          { colSpan: 24, type: 'select', key: 'departmentId', value: '', isRequired: true, disabled: false, label: '所属部门：', labelWidth: '90px', option: []},
          { colSpan: 24, type: 'select', key: 'roleIds', value: '', isRequired: true, disabled: true, label: '用户角色：', labelWidth: '90px', option: []},
          { colSpan: 24, type: 'select', key: 'status', value: '', isRequired: true, disabled: false, label: '账号状态：', labelWidth: '90px', option: [{ name: '正常', id: 2}, { name: '禁用(无法登录)', id: 3}]}
        ]
        // getAccount({
        //   id: obj.id
        // }).then(res => {
        //   if (res.code === 0) {
        //     let data = res.data
        //     data.roleIds = data.roleIds*1
        //     data.password = ''
        //     this.propSelect({
        //       key: 'platformMainbodyId',
        //       value: data.platformMainbodyId
        //     })
        //     this.initPropForm(type, data)
        //     this.propOptions.isShow = true
        //   }
        // })
      } else if (type === 'delet') {
        // this.$confirm('确定要删除该账号吗？?', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   delAccount({
        //     id: obj.id
        //   }).then(res => {
        //     if (res.code === 0) {
        //       this.$message({
        //         message: '删除成功',
        //         type: 'success'
        //       });
        //       this.getTableList()
        //     }
        //   });
        // }).catch(() => {});
      }
    },
    // 初始化弹窗表单数据
    initPropForm(type, obj) {
      this.propformHeard.forEach((item, index) => {
        if (type === 'add') {
          item.value = ''
        } else {
          item.value = obj[item.key]
        }
      })
    }
  }
};
</script>

<style lang="scss">
@import "./index.scss";
</style>